<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>两侧广告跟随</title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }
        
        body {
            height: 3000px;
        }
        
        #img1 {
            float: left;
            position: absolute;
        }
        
        #img2 {
            float: right;
            position: relative;
        }
        
        #img1,
        #img2 {
            margin-top: 200px;
            width: 100px;
            height: 300px;
            background-color: pink;
        }
        
        #header {
            width: 100%;
            height: 50px;
            background-color: black;
        }
        
        .contain {
            width: 600px;
            height: 2800px;
            margin: 30px auto;
            background-color: purple;
        }
    </style>
</head>

<body>
    <img id="img1">
    <img id="img2">
    <div id="header">
        <img class="header">
    </div>
    <div class="contain">

    </div>
    <script>
        function scroll() {
            if (window.pageYOffset !== undefined) {
                return {
                    left: window.pageXOffset,
                    top: window.pageYOffset
                }
            } else if (document.compatMode === 'CSS1Compat') {
                return {
                    left: document.documentElement.scrollLeft,
                    top: document.documentElement.scrollTop
                }
            }
            return {
                left: document.body.scrollLeft,
                top: document.body.scrollTop
            }
        }

        function animate(ele, target) {
            clearInterval(ele.timer)
            ele.timer = setInterval(function() {
                var step = (target - ele.offsetTop) / 10
                step = step > 0 ? Math.ceil(step) : Math.floor(step)
                if (ele.offsetTop >= target) {
                    ele.style.top = target + 'px'
                    clearInterval(ele.timer)
                }
                ele.style.top = ele.offsetTop + step + 'px'
            }, 10);
        }



        var imgArr = document.getElementsByTagName("img");
        window.onscroll = function() {
            var val = scroll().top;
            animate(imgArr[0], val - 163);
            animate(imgArr[1], val - 163);
        }
    </script>
</body>

</html>